package com.melon.modules.exception.integeration;

import com.melon.modules.exception.entity.ErrorInfo;
import com.melon.modules.exception.entity.MyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;

/***
 * 业务异常处理,
 * 切面技术的应用，允许你对Controller中抛出的某个或某些异常进行捕获并响应输出
 * 笔者以往的开发习惯，使用@ControllerAdvice捕获应用级别的异常，
 * 使用web.xml中的error-page配置处理容器级别的报错。
 * 假设定义的过滤器抛出的异常，@ControllerAdvice是无法处理的。
 *改用Spring Boot后，@ControllerAdvice没有捕获的异常，ErrorController会帮你“捡起来”。
 */
//@ControllerAdvice
class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    /*@ExceptionHandler(value = MyException.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }*/

    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, MyException e) throws Exception {
        ErrorInfo<java.lang.String> errorInfo = new ErrorInfo<>();
        errorInfo.setMessage(e.getMessage());
        errorInfo.setCode(ErrorInfo.ERROR);
        errorInfo.setData("Some data");
        errorInfo.setUrl(req.getRequestURL().toString());
        return errorInfo;
    }

}
